export default {
  state: {
    list: [], //购物车数据
    selectList: [], //选中的数据
  },
  getters: {
    isCheckAll(state) {
      console.log(state.list.length, state.selectList.length)
      if (state.list.length < state.selectList.length) {
        state.selectList.length = state.list.length
      }
      return state.list.length == state.selectList.length
    },
    // 计算数量和价格
    total(state) {
      let total = {
        num: 0,
        price: 0,
      }
      state.list.forEach((item) => {
        if (item.checked) {
          total.num += Number(item.good_num)
          total.price += item.good_price * item.good_num
        }
      })
      return total
    },
  },
  mutations: {
    // 获取购物车列表
    cartList(state, cartArr) {
      state.list = cartArr.reverse()
      cartArr.forEach((item) => {
        state.selectList.push(item.id)
      })
      // if (state.selectList < state.list) {
      //   state.selectList = state.list
      // }
    },
    // 全选
    checkAll(state) {
      state.selectList = state.list.map((item) => {
        item.checked = true
        return item.id
      })
    },
    // 全不选
    unCheckAll(state) {
      state.list.forEach((item) => {
        item.checked = false
      })
      state.selectList = []
    },
    // 单选
    checkItem(state, index) {
      console.log(index)
      let id = state.list[index].id
      let i = state.selectList.indexOf(id)
      if (i > -1) {
        // 表示能在selectList找的对应id，就删除
        return state.selectList.splice(i, 1)
      } else {
        // 如果之前没有选中，就添加一个id进去
        state.selectList.push(id)
      }
    },
  },

  actions: {
    // 忘记{}
    checkAllFn({ commit, getters }) {
      getters.isCheckAll ? commit("unCheckAll") : commit("checkAll")
    },
  },
}
